
import time

import dexen

from libs import input_reading
                             
class DevelopmentScript(dexen.Script):
    def __initialize__(self):
        self.boxes = input_reading.read_input()
        self.nboxes = len(self.boxes)            

    def __hasinput__(self):
        return True

    def __isinput__(self, ind):
        return ind.genotype != None and ind.phenotype == None 

    def __execute__(self, inds):
        print "I am in development"     
        for ind in inds:
            self.calculate(ind)
        return inds

    def is_left(self, item1, item2):
        return item1['x'] < item2['x'] and item1['y'] < item2['y']
    
    def is_below(self, item1, item2):
        return item1['x'] < item2['x'] and item1['y'] > item2['y']
    
    def calculate(self, ind):
        genotype = ind.genotype
        phenotype = [None] * self.nboxes
        # The indices are not referring to the indices of boxes 
        gamma_x = genotype['gamma_x']
        gamma_y = genotype['gamma_y']
        # The indices refers to the actual indices in boxes 
        encoding = genotype['encoding']
        orient = genotype['orient']
        for i in range(self.nboxes):
            phenotype[i] = {}    
        # Calculates the x coordinates of boxes      
        phenotype[gamma_x[0]]["x"] = 0
        for i in range(1, self.nboxes):
            box1_no = gamma_x[i]
            max_found = 0
            for j in range(0, i):
                box2_no = gamma_x[j]
                side = 0
                if self.is_left(encoding[box2_no], encoding[box1_no]):
                    if orient[box2_no] == 0:
                        side = self.boxes[box2_no]['w']
                    else:
                        side = self.boxes[box2_no]['h']
                    if phenotype[box2_no]['x'] + side > max_found:
                        max_found = phenotype[box2_no]['x'] + side
            phenotype[box1_no]["x"] = max_found
        # Calculates the y coordinates of boxes
        phenotype[gamma_y[self.nboxes - 1]]['y'] = 0
        for i in range(self.nboxes-2, -1, -1):
            max_found = 0
            box1_no = gamma_y[i]
            for j in range(i + 1, self.nboxes):
                box2_no = gamma_y[j]
                side = 0
                if self.is_below(encoding[box2_no], encoding[box1_no]):
                    if (orient[box2_no] == 0):
                        side = self.boxes[box2_no]['h']
                    else:
                        side = self.boxes[box2_no]['w']
                    if phenotype[box2_no]['y'] + side > max_found:
                        max_found = phenotype[box2_no]['y'] + side
            phenotype[box1_no]['y'] = max_found                
        ind.phenotype = phenotype


